Shadowing occurs when a local variable has the same name as a variable, field, or enum case
in an outer scope.
This can lead to three main problems:
- Confusion: The same name can refer to different variables in different parts of the scope, making the code hard to read and understand.
- Unintended Behavior: You might accidentally use the wrong variable, leading to hard-to-detect bugs.
- Maintenance Issues: If the inner variable is removed or renamed, the code’s behavior might change unexpectedly because the outer variable is
now being used.
To avoid these problems, rename the shadowing, shadowed, or both identifiers to accurately represent their purpose with unique and meaningful
names. It improves clarity and allows reasoning locally about the code without considering other software parts.
This rule focuses on variables shadowing fields or enum case
s.
Noncompliant code example
public class Foo {
public var myField:Int = 0
public func doSomething() {
var myField = 0 /// Noncompliant
// ...
}
}